from app.utils.cache import RedisCache
from app.utils.database import DatabasePool
from app.utils.logger import logger


class TeacherService:
    def __init__(self):
        self.cache = RedisCache()

    async def handle(self, data):
        index = data["raw_message"].index("老师")
        teacher_name = data["raw_message"][max(0, index - 5):index].strip()
        cached_result = await self.cache.get(f"teacher:{teacher_name}")
        if cached_result:
            logger.info(f"Cache hit for {teacher_name}")
            return cached_result
        else:
            result = await self.query_database(teacher_name)
            await self.cache.set(f"teacher:{teacher_name}", result, ttl=3600)
            return result

    @staticmethod
    async def query_database(name):
        try:
            conn = await DatabasePool.get_connection()
            cursor = await conn.cursor()

            await cursor.execute(""" 
            SELECT name, department, telephone, landline, email 
            FROM data 
            WHERE name = ? 
        """, (name,))
            results = await cursor.fetchall()
            if results:
                # 格式化查询结果
                messages = []
                for result in results:
                    name, department, telephone, landline, email = result
                    message = (
                        f"--海大通讯录--\n"
                        f"姓名：{name}\n"
                        f"部门：{department}\n"
                        f"手机：{telephone}\n"
                        f"电话：{landline}\n"
                        f"邮箱：{email}"
                    )
                    messages.append(message)
                    # 将所有结果合并为一个消息字符串
                    final_message = "\n\n".join(messages)  # 用两个换行符分隔每位老师的信息
                    return final_message
            else:
                # 如果没有找到结果，返回一个提示信息
                final_message = "未找到相关老师信息"
                return final_message

        except Exception as e:
            logger.error(f"Error querying the database: {e}")
            return "数据库查询失败"
